<?php

namespace plugin\admin\app\common\xbuilder;

use plugin\admin\app\common\xbuilder\widget\FormItemType;

/**
 * XBuilderForm动态表单
 * "horizontal": {
 * "leftFixed": "xs"
 * }
 */
class XBuilderForm
{
    // 数据
    private $form= [
        'title' => '',
        'type' => 'form',
        'api' => [],
        'data' => [],
        "mode" => "horizontal",  //horizontal , inline
        "wrapWithPanel" => false,
        "affixFooter" => false,
        'controls' => []
    ];
    private $buttons;
    private $group = null;
    private $_tabsSubItem = null;  //FormItem类型为tabs
    private $_tabsItem = [
        'type'=>'tabs',
        'tabs'=>[],
    ];  //FormItem类型为tabs
    private $_template = '../extend/garden/xbuilder/layout/temple/form.html'; // 模版
    private $_tab_nav  = [];  //tabs切换框数据

    public function setMetaTitle($title)
    {
        $this->form['title'] = $title;
        return $this;
    }

    /**
     * @param string $mode horizontal单行横行排列 , inline所有行横向排列
     * @return $this
     */
    public function setFormMode($mode = 'horizontal', $modeCofnig = null)
    {
        $this->form['mode'] = $mode;
        if (!empty($modeCofnig) && $mode === 'horizontal') {
            $this->form['horizontal'] = $modeCofnig;
        }
        return $this;
    }

    /**
     * 固定底部含有按钮的footer栏
     * @param bool $mode
     * @return $this
     */
    public function setFooterAffix($mode = true)
    {
        $this->form['affixFooter'] = $mode;
        return $this;
    }

    public function setFormData($form_data, $bug = false)
    {
        $this->form['data'] = $form_data;
        if ($bug) {
            $this->form['debug'] = $bug;
        }
        return $this;
    }
    /**
     * exp1:
    [
        'title'=>'栏目1',
        'body'=>'栏目1内容',
    ],
    [
        'title'=>'栏目2',
        'body'=>'栏目2内容',
    ]
     * exp2:
    setTabNav('tab栏目1',$tab1)
     * @param $title
     * @param $data
     * @return $this
     */
    public function setTabNav($title, $data = [])
    {
        if(is_array($title)){
            $this->_tab_nav = $title;
        } else {
            $this->_tab_nav[] = [
                'title'=>$title,
                'body'=>$data
            ];
        }
        return $this;
    }
    /**
     * 设置表单提交地址
     * @param $post_url 提交地址
     * @param $method 提交类型
     * @param $redirect 提交后跳转地址
     * @return $this
     *
     */
    public function setFormUrl($type = '', $method = 'post', $redirect = '')
    {
        $url = get_curent_path('api'). "/$type" . '?id=${id}';
        $api = [
            'method' => $method,
            'url' => $url,
            'headers' => [
                'X-Requested-With' => 'XMLHttpRequest'
            ],
//            'data' => [   //只提交变更字段
//                'diff' => "\${diff}"
//            ]
        ];
        $this->form['api'] = $api;
        if ($redirect) {
            $this->form['redirect'] = (string)$redirect;
        }
        return $this;
    }

    /**
     * 设置表单按钮动作 TODO 1. actionType映射的组件名称
     * @param $title
     * @param string $attr ['api'=>'https://xxx','level'=>'link、primary、secondary、info、success、warning、danger、light、dark、default','icon'=>'fa fa-plus','size'=>'xs、sm、md、lg']
     * @param string $actionType ajax、link、url、drawer、dialog、confirm、cancel、prev、next、copy、close
     * @param null $actionContent
     * @return $this
     */
    public function setActions($title, $attr = 'info', $actionType = '', $actionContent = null)
    {

        $button = [
            'label' => $title,
            'type' => 'action',
            'level' => 'info',
            'actionType' => $actionType
        ];
        if (is_array($attr)) {
            $button = array_merge($button,$attr);
        } else {
            $button['level'] = $attr;
        }
        if($actionType){
            $button['actionType'] = $actionType;
            $button[$actionType] = $actionContent;
        }
        if ($this->buttons && is_array($this->buttons)) {
            $this->buttons[] = $button;
        } else {
            $this->buttons = $button;
        }
        $this->form['actions'] = $this->buttons;
        return $this;
    }

    public function addGroup($type = 'group')
    {
        $this->group = [];
        $this->group['type'] = $type;
        return $this;
    }
    public function endGroup()
    {
        $this->form['controls'][] = $this->group;
        $this->form['controls'][] = ['type' => 'divider'];
        $this->group = null;
        return $this;
    }
    /**
     * 添加amis中的FormItem表单元素
     * @param $name
     * @param $type
     * @param $title ['title'=>'','size'=>'xs/sm/md/lg/full(input宽度)','remark'=>'','placeholder'=>'']
     * @param false $required [
        'required'=>true,
        'rule'=>[
            'isNumeric'=>true,
            'minimum'=>1
        ],
        'errMsg'=>[
            'isNumeric'=>'请输入数字',
            'minimum'=>'最小数字为1'
        ]
    ]
     * @param array $options
     * @param string $extra
     * @param string $extra_attr
     * @return $this
     */
    public function addFormItem($name, $type, $title, $required = false, $hidden = false)
    {
        $item = FormItemType::getFormItem($name, $type, $title, $required, $hidden);
        if (is_array($this->group)) {   //分组
            $this->group['controls'][] = $item;
        } else if (is_array($this->_tabsSubItem)){ //分tab页
            $this->_tabsSubItem['controls'][] = $item;
        } else {
            $this->form['controls'][] = $item;
//            $this->form['controls'][] = ['type' => 'divider'];
        }
        return $this;
    }

    //配置tabs中的标题及内容
    public function addTabsGroup($title = 'tab标题')
    {
        $this->_tabsSubItem = [];
        $this->_tabsSubItem['title'] = $title;
        return $this;
    }
    //结束addTabsGroup
    public function endTabsGroup()
    {
        $this->_tabsItem['type'] = 'tabs';
        $this->_tabsItem['tabs'][] = $this->_tabsSubItem;
        $this->_tabsSubItem = null;
        return $this;
    }
    //配置tabs位置：配置类型为tabs的FormItem,把每个addTabsGroup及endTabsGroup包裹的tab项插入到表单相应位置
    public function addTabsItem(){
        $this->form['controls'][] = $this->_tabsItem;
        $this->_tabsItem = null;
        return $this;
    }
    public function addFormItems($items = []){
        $datas = [];
        foreach ($items as $item){
            $title = $item['title'] ?: $item['label'];
            if(!$item['options'][0]){
                unset($item['options']);
            }
            $datas[] = FormItemType::getFormItem($item['name'], $item, $title);
        }
        $this->form['controls'] = array_merge($this->form['controls'],$datas);
        return $this;
    }
    /**
     * 返回form数据
     */
    public function getFormData()
    {
        return $this->form;
    }
    /**
     * 返回buttons数据
     */
    public function getButtonData()
    {
        return $this->buttons;
    }

    public function display()
    {
        $formConfig = $this->getFormData();
        if(!empty($this->_tab_nav)){
            $tabKey = 0;
            $formConfig = [
                'title'=>'',
                'type'=>'page',
                'body'=>[
                    'type'=>'tabs',
                    "activeKey"=>$tabKey,
                    'mode'=>'line',
                    'tabs'=>$this->_tab_nav
                ]
            ];
        }
        return view($this->_template,['pageConfigs'=>$formConfig, 'meta_title'=>$formConfig['title']]);
    }
}
